#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/11 11:00
# @Author  : CoderCharm
# @File    : role.py
# @Software: PyCharm
# @Desc    :
"""
角色表crud操作
"""

from typing import Optional
from sqlalchemy.orm import Session
from sqlalchemy import func, or_

from api.common.curd_base import CRUDBase
from api.models.auth import AdminRole,Role
from ..schemas import role_schema


class CRUDRole(CRUDBase[AdminRole, role_schema.RoleCreate, role_schema.RoleUpdate]):

    @staticmethod
    def query_role(db: Session, *, role_id: int) -> Optional[AdminRole]:
        """
        此role_id是否存在
        :param db:
        :param role_id:
        :return:
        """
        return db.query(AdminRole).filter(AdminRole.role_id == role_id).first()

    def create(self, db: Session, *, obj_in: role_schema.RoleCreate) -> Role:
        db_obj = Role(
            name=obj_in.name,
            pid=obj_in.pid
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    #分页查询所有{"total":100,'list':reslit}
    @staticmethod
    def queryall_role(db: Session, *, page: int,page_size:int) -> dict:
        """
        此role_id是否存在
        :param db:
        :param role_id:
        :return:
        """
        #获取共有多少条记录

        #获取当前页面的数据
        #封装返回

        #偏移量计算
        temp_page = (page -1) * page_size

        # 查询数量 select count(id) from role where is_delete=0
        total = db.query(func.count(Role.id)).filter(Role.is_delete == 0).scalar()
        # 查询结果集select * from role limit 0,取几条
        query_obj = db.query(Role).filter(Role.is_delete == 0).offset(
            temp_page).limit(page_size).all()
        
        items = [{"id": obj.id, 'create_time': obj.create_time.strftime('%Y-%m-%d %H:%M:%S'), "name": obj.name} for obj in query_obj]
        return {
            "items": items,
            "total": total
        }

    @staticmethod
    def getMenu(db: Session, *,roleid:int) -> list:
        role = db.query(Role).filter(Role.id == roleid).first()
        sql = "select res.id,res.name,res.pid,res.url,pres.name as pname,res.promition from resource as res left join resource as pres on res.pid=pres.id where res.restype=2 and res.pid>0"
        print(sql)
        res = db.execute(sql)
        list=[]
        for i in res:
            flag = role.promition & i.promition
            if flag > 0:
                list.append(i)
        return list

curd_role = CRUDRole(AdminRole)
